<!-- 时间筛选 -->
<template>
  <el-form-item label="统计单位：">
    <el-select
      v-model="form.type"
      @change="change"
    >
      <el-option
        v-for="item in units"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </el-form-item>
  <el-form-item label="时间范围：">
    <el-row>
      <el-col :span="11">
        <el-date-picker
          v-model="form.startDate"
          :type="form.type === 'day'?'date': form.type"
          style="width: 100%;"
          placeholder="开始日期"
          :disabled-date="disabledDate"
          @focus="focus(1)"
        />
      </el-col>
      <el-col
        class="flex justify-center"
        :span="2"
      >
        -
      </el-col>
      <el-col :span="11">
        <el-date-picker
          v-model="form.endDate"
          :type="form.type === 'day'?'date': form.type"
          style="width: 100%;"
          placeholder="结束日期"
          :disabled-date="disabledDate"
          @focus="focus(2)"
        />
      </el-col>
    </el-row>
  </el-form-item>
</template>
<script>
import dayjs from 'dayjs'
export default {
  name: 'AppTimeChange'
}
</script>
<script setup>

const units = ref([{
  value: 'day',
  label: '日'
}, {
  value: 'month',
  label: '月'
}, {
  value: 'year',
  label: '年'
}])
const form = reactive({
  type: 'day',
  startDate: null,
  endDate: null
})

onMounted(() => {
  form.startDate = dayjs().date(1).startOf('day').toDate()
  form.endDate = dayjs().endOf('day').toDate()
})

const change = () => {
  form.startDate = null
  form.endDate = null
}

const inputNum = ref(null)
// 选择的时间框
const focus = (flag) => {
  inputNum.value = flag
}
// 时间禁用
const disabledDate = (time) => {
  if (inputNum.value === 1) {
    if (!form.endDate) return time.getTime() > Date.now()
    return time.getTime() > form.endDate.getTime() || time.getTime() > Date.now()
  } else {
    if (!form.startDate) return time.getTime() > Date.now()
    return time.getTime() < form.startDate.getTime() || time.getTime() > Date.now()
  }
}

// 获取时间
const getTime = () => {
  const type = form.type
  return {
    startDate: form.startDate ? dayjs(form.startDate).startOf(type).format('YYYY-MM-DD HH:mm:ss') : null,
    endDate: form.endDate ? dayjs(form.endDate).endOf(type).format('YYYY-MM-DD HH:mm:ss') : null,
    type
  }
}

// 向外暴露getTime
defineExpose({
  getTime
})
</script>

<style scoped lang='scss'>

</style>
